/*
 * @Author: CodeHare
 * @Date: 2023-09-20 18:09:21
 * @LastEditors: yangni 920556271@qq.com
 * @LastEditTime: 2024-05-14 13:59:45
 * @Description: 告警详情页
 */
// ignore_for_file: avoid_print, unrelated_type_equality_checks
import 'package:get/get.dart';
import 'package:native_dart_package/http/request/exception/exception_handler.dart';
import 'package:native_dart_package/native_dart_package.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/configs.dart';
import 'package:yt_devops/pages/alarm/alarm_detail/alarm_detail_model.dart';
import 'package:yt_devops/pages/alarm/alarm_home/alarm_home_controller.dart';
import 'package:yt_devops/pages/devices/device_list/device_list_model.dart';
import 'package:yt_devops/pages/tabs/home_tab/main_home/main_home_controller.dart';
import 'package:yt_devops/routers/router_path.dart';
import 'package:yt_devops/services/alarm/alarm_services.dart';
import 'package:yt_devops/user_entity_manager.dart';
import 'package:yt_devops/utils/alarm_util.dart';
import 'package:yt_devops/utils/enums.dart';
import 'package:yt_devops/utils/navigate_utils.dart';

import '../../../resources/str_res_keys.dart';
import '../../../services/device/device_sevices.dart';

class AlarmDetailController extends GetxController {
  AlarmHomeController alarmHomeController = AlarmHomeController();
  AlarmDetailModel model = AlarmDetailModel();
  AlarmServices alarmServices = Get.find();
  Map<String, dynamic> params = {};
  String? repairSuggestion;
  bool canShow = false;
  bool isCleanUp = false;

  /// 角色
  late int role;
  late List<num> alarmIds = [];

  /// 源头
  late int id;

  @override
  void onInit() {
    super.onInit();

    id = Get.arguments?['id'];
    alarmIds.add(id);
    readCacheRole();
    loadDetail(id);
  }

  /// 读取缓存角色
  void readCacheRole() {
    // var roles = UserEntityManager().load().roles;
    // Log.d('roles==' + roles.toString());
    role = UserEntityManager().roleID!;
  }

  /// 请求详情数据
  void loadDetail(int id) => Configs.httpClient.requestWithLoading(
        () async {
          var params = {"id": id};
          await alarmServices.getAlarmDetail(params).then((value) {
            model = AlarmDetailModel.fromJson(value);
            update();
          }, onError: (err) {
            dismissLoading();
            handleException(err);
            return false;
          });
        },
      );

  @override
  void onReady() {}

  ///需要先去获取设备的子设备列表,不然无法订阅子设备状态
  getSubDevicesIdList() async {
    showLoading(toast: ResKey.loading.tr);
    var result = await alarmServices.getSubDevice({
      'deviceId': model.parentId,
    }, onError: (e) {
      dismissLoading();
      showError(e.message.toString());
      return false;
    });
    dismissLoading();
    Log.d('requestSubDevicesIdList===$result');
    List<int> subDevicesIdList = [];
    List<String> subDevicesNameList = [];
    if (result != null && result['children'] != null) {
      List children = result['children'];
      if (children.isNotEmpty) {
        for (var element in children) {
          subDevicesIdList.add(element['id']);
          subDevicesNameList.add(element['name'].toString());
          element['childDeviceList'] = element['children'];
          element['deviceId'] = element['id'];
          element['productType'] = element['productTypeId'];
          for (var child in (element?['children'] ?? [])) {
            child['childDeviceList'] = child['children'];
            child['deviceId'] = child['id'];
            child['productType'] = child['productTypeId'];
          }
        }
      }
      result['childDeviceList'] = result['children'];
      result['deviceId'] = result['id'];
      result['productType'] = result['productTypeId'];
      if (subDevicesIdList.isNotEmpty) {
        // model.deviceId = subDevicesIdList.first;
        subDevicesIdList.removeAt(0);
        subDevicesNameList.removeAt(0);
      }
    }
    Log.d('productId==' + model.productId.toString());
    AlarmUtil.fromModule = AlarmFromWhereType.device.value;
    NavigateUtils.toDeviceDetail(model.alarmDeviceId!, model.productType!,
            model.deviceName!, model.connectStatus!,
            productId: model.productId!,
            subDevicesIdList:
                subDevicesIdList.isNotEmpty ? subDevicesIdList : [],
            subDevicesNameList:
                subDevicesNameList.isNotEmpty ? subDevicesNameList : [],
            deviceTree:
                result == null ? null : DeviceListModel.fromJson(result))
        ?.then((value) {
      AlarmUtil.fromModule = AlarmFromWhereType.currentSite.value;
    });
  }

  @override
  void onClose() {}
}
